"""
详细API测试脚本
创建时间：2025-09-21
作者：开发团队
目的：详细测试API请求和响应
"""

import requests
import json

# API基础URL
BASE_URL = "http://127.0.0.1:8000/api/v1"

def test_login_api():
    """测试登录API"""
    print("测试登录API...")
    
    # 测试数据
    login_data = {
        "username": "guard001",
        "password": "123456",
        "remember": False
    }
    
    print(f"请求URL: {BASE_URL}/auth/login")
    print(f"请求数据: {login_data}")
    
    try:
        # 发送登录请求
        response = requests.post(f"{BASE_URL}/auth/login", json=login_data)
        print(f"响应状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")
        print(f"响应内容: {response.text}")
        
        if response.status_code == 200:
            try:
                data = response.json()
                print(f"解析后的JSON数据: {data}")
                
                # 检查响应码
                if data.get('code') == 200:
                    print(f"登录成功!")
                    token = data.get('data', {}).get('token')
                    user_info = data.get('data', {}).get('user')
                    print(f"Token: {token}")
                    print(f"用户信息: {user_info}")
                    return token
                else:
                    print(f"登录失败: {data.get('message')}")
                    print(f"错误信息: {data.get('error')}")
                    return None
            except json.JSONDecodeError as e:
                print(f"JSON解析错误: {e}")
                return None
        else:
            print(f"HTTP错误: {response.status_code}")
            return None
            
    except Exception as e:
        print(f"登录请求出错: {e}")
        import traceback
        traceback.print_exc()
        return None

def test_headers():
    """测试请求头"""
    print("\n测试请求头...")
    
    # 测试数据
    login_data = {
        "username": "guard001",
        "password": "123456",
        "remember": False
    }
    
    # 测试不同的请求头
    headers_list = [
        {"Content-Type": "application/json"},
        {"Content-Type": "application/json", "Accept": "application/json"},
        {},  # 无请求头
    ]
    
    for i, headers in enumerate(headers_list):
        print(f"\n测试请求头 {i+1}: {headers}")
        try:
            response = requests.post(f"{BASE_URL}/auth/login", json=login_data, headers=headers)
            print(f"  响应状态码: {response.status_code}")
            if response.status_code == 200:
                try:
                    data = response.json()
                    print(f"  响应码: {data.get('code')}")
                    print(f"  消息: {data.get('message')}")
                except:
                    print(f"  响应内容: {response.text[:100]}...")
            else:
                print(f"  错误内容: {response.text[:100]}...")
        except Exception as e:
            print(f"  请求出错: {e}")

def main():
    print("详细API测试")
    print("=" * 50)
    
    # 测试登录API
    token = test_login_api()
    
    # 使用token变量避免未使用警告
    if token:
        print(f"获取到token: {token[:20]}..." if len(token) > 20 else f"获取到token: {token}")
    else:
        print("未获取到有效token")
    
    # 测试请求头
    test_headers()
    
    print("\n测试完成")

if __name__ == "__main__":
    main()